﻿using System;
using System.Windows.Input;

namespace DebIt.ViewModel
{
    public class PhoneCommand<T> : ICommand
    {
        #region Fields

        readonly Action<T> _execute;
        readonly Predicate<T> _canExecute;
        private bool _canExecuteCache;
        public event EventHandler CanExecuteChanged;

        #endregion


        #region Constructors

        public PhoneCommand(Action<T> execute) : this(execute, null) { }

        public PhoneCommand(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null) { throw new ArgumentNullException("execute"); }
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion


        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
                return true;
            bool tmp = _canExecute((T)parameter);
            if (tmp != _canExecuteCache)
            {
                _canExecuteCache = tmp;
                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());
            }
            return _canExecuteCache;
        }



        public void Execute(object parameter)
        {
            if (CanExecute(parameter))
                _execute((T)parameter);
        }

        #endregion
    }
}
